<?php
namespace App\Repositories\BLL;

use App\Repositories\BLL\Repository;
use App\Models\Admins\Role;
use Illuminate\Support\Facades\DB;

class RoleBLL extends Repository
{
    public function model()
    {
        return Role::class;
    }

    public function ajaxIndex($currentRouteName)
    {
        // datatables请求次数
        $draw = request()->input('draw', 1);
        // 开始条数
        $start = request()->input('start', config('admin.global.list.start'));
        // 每页显示数目
        $length = request()->input('length', config('admin.global.list.length'));
        // 排序
        $order['name'] = request()->input('columns.' .request()->input('order.0.column', 0) . '.name');
        $order['dir'] = request()->input('order.0.dir', 'asc');

        $search['value'] = request()->input('search.value', '');

        $search['regex'] = request()->input('search.regex', false);

        $role = $this->model;

        // 搜索框中的值
        if ($search['value']) {
            if ($search['regex'] == 'true') {
                $role = $role->where('name', 'like', "%{$search['value']}%")->orWhere('display_name', 'like', "%{$search['value']}%");
            } else {
                $role = $role->where('name', $search['value'])->orWhere('display_name', $search['value']);
            }
        }

        $count = $role->count();

        $role = $role->orderBy($order['name'], $order['dir']);
        $roles = $role->offset($start)->limit($length)->get();

        $pointPost = strrpos($currentRouteName, '.');
        $parentUrl = substr($currentRouteName, 0, $pointPost);
        if ($roles) {
            foreach ($roles as &$v) {
                $v->actionButton = $v->getListActionButton($currentRouteName).$this->getAuthButton($parentUrl, $v->id);
            }
        }

        //datatables固定返回格式
        return [
            'draw' => $draw,
            'recordsTotal' => $count,
            'recordsFiltered' => $count,
            'data' => $roles,
        ];
    }

    private function getAuthButton($parentUrl, $id)
    {
        $thisUrl = $parentUrl.'.auth';
        if (sp_check_auth($thisUrl)) {
            return '<a class="btn btn-info btn-xs" href="'.route($thisUrl, ['id'=>$id]).'"><i class="fa fa-edit"></i> 权限</a> ';
        }
        return '';
    }

    public function createEntity($attributes)
    {
        $result = $this->create($attributes);
        if ($result) {
            flash('添加角色成功');
        } else {
            flash('添加角色失败', 'error');
        }
        return $result;
    }

    public function editView($id)
    {
        $role = $this->find($id);
        if ($role) {
            return $role;
        }
        abort(404);
    }

    public function updateEntity($attributes, $id)
    {
        $result = $this->update($attributes, $id);
        if ($result) {
            flash('修改角色成功');
        } else {
            flash('修改角色失败', 'error');
        }
        return $result;
    }

    public function destroyEntity($id)
    {
        //		$result = $this->delete($id);
        //entrust的bug，不能用上面的方法。。。原因不找了。
        $result = Role::whereId($id)->delete();
        if ($result) {
            flash('修改角色成功');
        } else {
            flash('修改角色失败', 'error');
        }
        return $result;
    }

    /**
     * 获取所有角色
     */
    public function getAllEntity()
    {
        $roles = $this->all();
        return $roles;
    }

    public function getPermissionByRole($id)
    {
        $result = DB::table('permission_role')
            ->select('permission_id')
            ->where('role_id', '=', $id)
            ->get();
        return $result;
    }

    public function postAuth($attributes, $id)
    {
        $result = false;
        //删除原始资料
        DB::table('permission_role')->where('role_id', '=', $id)->delete();

        //新增
        $role = $this->find($id);
        if ($role) {
            $result = $role->perms()->sync($attributes['menuid']);
            if ($result) {
                flash('权限赋予成功');
            } else {
                flash('权限赋予失败', 'error');
            }
        } else {
            flash('角色未找到，权限赋予失败', 'error');
        }

        return $result;
    }
}
